from exts import db
from datetime import datetime


class UserModel(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(200), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    # datetime.now：用户注册时的时间; datetime:服务器启动时的时间
    join_time = db.Column(db.DateTime, default=datetime.now)


class EmailCaptchaModel(db.Model):
    __tablename__ = "email_captcha"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(100), nullable=False)
    captcha = db.Column(db.String(100), nullable=False)
    # # used字段：仅仅只是判断captcha验证码是否被使用过
    # used = db.Column(db.Boolean, default=False)


class QuestionModel(db.Model):
    __tablename__ = "question"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)

    # db.String(100) 改成 db.Text，TEXT 专门存储大段文本的 MySQL 类型，支持最多 65,535 字符。
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)

    # 外键：发布问答，要绑定作者,需要外键ForeignKey，引用user表中的id属性，且author_id字段类型必须要和id类型保持一致
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    # 反向引用backref：通过user拿到该作者名下所有问答
    author = db.relationship(UserModel, backref="questions")


class AnswerModel(db.Model):
    __tablename__ = "answer"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)

    # 外键
    question_id = db.Column(db.Integer, db.ForeignKey("question.id"))
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))

    # ORM操作是用对象的方式进行操作，反向引用:
    # 通过question对象能够拿到该问答下的所有评论；且answer评论应该要按最新时间排序，所以要加上倒数排序
    question = db.relationship(QuestionModel, backref=db.backref("answers", order_by=create_time.desc()))
    # 也可以加上order_by=create_time.desc()，也可不加
    author = db.relationship(UserModel, backref=db.backref("answers"))
